package com.example.gulimall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.example.common.utils.R;
import com.example.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.example.gulimall.ware.entity.WareOrderTaskEntity;
import com.example.gulimall.ware.service.WareSkuService;
import com.example.gulimall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import to.mq.OrderTO;
import to.mq.StockDetailTo;
import to.mq.StockLockedTo;

import java.io.IOException;

@RabbitListener(queues = "stock.release.stock.queue")
@Service
public class StockReleaseListener {
    /**
     * 库存自动解锁
     *   下单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚，之前的库存就要自动解锁
     * 只要解锁库存的消息失败，一定要告诉rabbimq解锁失败
     * 处理消息
     */
    @Autowired
    WareSkuService wareSkuService;
    @RabbitHandler
    public void  handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁消息");
       try {
           wareSkuService.unLockStock(to);
           channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
       }catch (Exception e){
           channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
       }
    }
    @RabbitHandler
    public  void  handleOrderCloseRelease(OrderTO orderTO, Message message, Channel channel) throws IOException {
        System.out.println("订单关闭，准备解锁库存");
        try {
            wareSkuService.unLockStock(orderTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }
}
